package com.ysmygx.cosumer;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ysmygx.constants.AuthConstants;
import com.ysmygx.constants.OrderStatusConstants;
import com.ysmygx.dto.QueryPayStatusDTO;
import com.ysmygx.entity.AccountTransHisReq;
import com.ysmygx.entity.AccountTransHisResp;
import com.ysmygx.entity.OrderStatusResp;
import com.ysmygx.manage.BankManage;
import com.ysmygx.utils.BusinessException;
import com.ysmygx.utils.R;
import com.ysmygx.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author laoyanbin
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = "query-order-status-topic", consumerGroup = "query_order_status_consumer")
public class QueryOrderStatusConsumer implements RocketMQListener<String> {

    @Resource
    private BankManage bankManage;

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Value("${ysmygx.cloud.queryOrderStatusCallBackUrl}")
    private String callBackUrl;

    private static final int MAX_QUERY_PAY_TIMES = 15;

    /**
     * 委托加工费支付
     */
    public static final int TYPE_PAY_PROCESS = 1;
    /**
     * 委托加工费提现
     */
    public static final int TYPE_WITHDRAW_PROCESS = 2;
    /**
     * 支付原木款
     */
    public static final int TYPE_PAY_WOOD = 3;
    /**
     * 原木采购款提现
     */
    public static final int TYPE_WITHDRAW_BUYER = 4;

    @Override
    public void onMessage(String message) {
        ThreadLocalUtil.set(UUID.fastUUID().toString(true));
        log.info("{},接收到查询支付状态消息：{}",ThreadLocalUtil.get(), message);
        try {
            QueryPayStatusDTO dto = JSONUtil.toBean(JSONUtil.parseObj(message).getStr("body"), QueryPayStatusDTO.class);

            Integer queryTimes = dto.getQueryTimes();
            String orderFlowNo = dto.getOrderFlowNo();

            OrderStatusResp orderStatusResp = bankManage.queryOrderStatus(orderFlowNo);


            if (OrderStatusConstants.ORDER_STATE_SUCCESS.equals(orderStatusResp.getOrderState())){

            }else if(OrderStatusConstants.ORDER_STATE_FAIL.equals(orderStatusResp.getOrderState())){

            }else{
                //非 成功、失败 状态都认为是中间状态

                //判断查询次数是否超过预设值，如果超过预设值，则记录异常
                if (queryTimes>MAX_QUERY_PAY_TIMES){
                    log.error("查询支付状态次数过多,支付流水号orderFlowNo：{}",orderFlowNo);
                }else{
                    //正在处理中，再次发送延迟消息进行查询
                    queryTimes++;

                    QueryPayStatusDTO msgBodyDto = new QueryPayStatusDTO();
                    msgBodyDto.setType(dto.getType());
                    msgBodyDto.setQueryTimes(queryTimes);
                    msgBodyDto.setOrderFlowNo(orderFlowNo);
                    msgBodyDto.setWalletDealId(dto.getWalletDealId());
                    msgBodyDto.setRecUserId(dto.getRecUserId());
                    msgBodyDto.setWalletDealId2(dto.getWalletDealId2());
                    msgBodyDto.setWithdrawId(dto.getWithdrawId());

                    Map bodyMap = new HashMap();
                    bodyMap.put("body", msgBodyDto);

                    // 构建消息
                    org.springframework.messaging.Message<String> messageSendBody = MessageBuilder.withPayload(JSONUtil.toJsonStr(bodyMap))
                            .build();

                    // 发送延迟消息
                    rocketMQTemplate.syncSend("query-order-status-topic", messageSendBody,1000000L,queryTimes);
                }
            }

            dto.setOrderStatus(orderStatusResp.getOrderState());
            dto.setOrderMessage(orderStatusResp.getOrderMessage());
            dto.setHostFlowNo(orderStatusResp.getHostFlowNo());
            //调用回调接口，把支付状态结果发送到服务器
            HttpResponse httpResponse = HttpRequest.post(callBackUrl).header("appid", AuthConstants.APPID).body(JSONUtil.toJsonStr(dto)).execute();
            if (!httpResponse.isOk() || JSONUtil.parseObj(httpResponse.body()).getInt("code")!=200){
                log.error("请求查询支付状态回调失败:{}", httpResponse.body());
//                throw new BusinessException("请求回调url异常");
            }
        }catch (Exception e){
            log.error("支付状态查询消息消费异常",e);
        }
    }
}






